//
//  UserMap.m
//  Ridding
//
//  Created by zys on 12-3-20.
//  Copyright 2012年 __MyCompanyName__. All rights reserved.
//

#import "UserMap.h"
#import "UIColor+XMin.h"
#import "ResponseCodeCheck.h"
@implementation UserMap
@synthesize mapView;
@synthesize route_view=_route_view;
@synthesize line_color;
@synthesize routes=_routes;
@synthesize requestUtil;

@synthesize userArray=_userArray;
@synthesize riddingId;
@synthesize staticInfo;
@synthesize lastLocation;
@synthesize myLocation=_myLocation;
@synthesize coordinate;
@synthesize isShowDelete;
@synthesize showingAnnotation;
@synthesize loadingView;
@synthesize getToDestinationTimer;
@synthesize sendMyLocationTimer;
@synthesize showTeamButton;

@synthesize startAnnotation;
@synthesize endAnnotation;

@synthesize backBtn=_backBtn;
@synthesize distanceLabel=_distanceLabel;
@synthesize toDistanceLabel=_toDistanceLabel;
@synthesize distanceSpeedView=_distanceSpeedView;

@synthesize showMemberButton=_showMemberButton;
@synthesize membersStatusView=_membersStatusView;
@synthesize showLocationButton=_showLocationButton;
@synthesize zoomInButton=_zoomInButton;
@synthesize zoomOutButton=_zoomOutButton;
@synthesize userTapView=_userTapView;
@synthesize userScrollView=_userScrollView;
@synthesize riddingStatus=_riddingStatus;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        requestUtil=[RequestUtil getSinglton];
        requestUtil.requestUtilDelegate=self;
        staticInfo=[StaticInfo getSinglton];
        self.myLocation = [[CLLocationManager alloc] init];
        [self.myLocation setDelegate:self];
        [self.myLocation setDesiredAccuracy:kCLLocationAccuracyBest];

    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    UITapGestureRecognizer *viewTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(mapViewClick:)]; //动态添加点击操作
    [self.userTapView addGestureRecognizer:viewTap];
    [mapView addGestureRecognizer:viewTap];
    _isUserTapViewOut=FALSE;
    _isAnimationing=FALSE;
    _routesInited=FALSE;
    _isShowTeamers = FALSE;
    _userInited=FALSE;
    [self myLocationQuartz];
    [self goToDestinationQuartz];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    dispatch_queue_t q;
    q=dispatch_queue_create("download", NULL);
    dispatch_async(q, ^{
        [NSThread sleepForTimeInterval:0.5];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self download];
        });
    });
}

-(void)download{
    loadingView=[[ActivityView alloc]init:@"初始化数据中" lat:self.view.frame.size.width/2 log:self.view.frame.size.height/2];
    [self.view addSubview:loadingView];
    [loadingView setHidden:NO];
    if(!_userInited){
        //异步去加载用户
        [self removeAllUserView];
        [self setUsers];
    }
    if(!_routesInited){
        //异步去画地图
        [self drawRoutes]; 
    }

}

- (void)viewWillDisappear:(BOOL)animated{
    self.myLocation.delegate=nil;
    requestUtil.requestUtilDelegate=nil;
    mapView.delegate=nil;
    self.userScrollView.delegate=nil;
    self.myLocation.delegate=nil;
    [sendMyLocationTimer invalidate];
    [getToDestinationTimer invalidate];
    for (UIView* view in [self.userScrollView subviews]) {
        if([view isKindOfClass:[UserView class]]){
            UserView *userView=(UserView*)view;
            userView.userViewDelegate=nil;
        }
    }
    [super viewWillDisappear:animated];
}



//得到我离终点的距离
-(void)getToDestinationDistance{
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray *array=[[RiddingLocationDao getSinglton] getRiddingLocations:riddingId beginWeight:[NSNumber numberWithInt:0]];
         if(!array||[array count]==0){
             return;
         }
         CLLocation* checkLocation=self.myLocation.location;
         CLLocationDistance nearestLength=-1;
         RiddingLocation *nearestLocation=nil;
         int index=0;
         for(int i=0;i<[array count];i++){
             RiddingLocation* location=(RiddingLocation*)[array objectAtIndex:i];
             CLLocation *alocation=[[CLLocation alloc]initWithLatitude:location.latitude longitude:location.longtitude];
             CLLocationDistance kilometers=[alocation distanceFromLocation:checkLocation]/1000;  
             if(kilometers < nearestLength||nearestLength==-1){
                 nearestLength=kilometers;
                 nearestLocation=location;
                 index=i;
             }
         }
         for(int i=index;i<[array count];i++){
             RiddingLocation* location=(RiddingLocation*)[array objectAtIndex:i];
             nearestLength+=[location.toNextDistance doubleValue];
         }
         dispatch_async(dispatch_get_main_queue(), ^{
             [self.toDistanceLabel setText:[NSString stringWithFormat:@"还有距离:%0.2lf km",nearestLength/1000]];
         });
     
     });
}


-(void)setUsers{
    dispatch_queue_t q;
    q=dispatch_queue_create("setUsers", NULL);
    dispatch_async(q, ^{
        NSArray *array = [requestUtil getUserList:riddingId];
        if(array&&[array count]>0){
            for(NSDictionary *auser in array){
                User *user=[[User alloc]init];
                user.userId = [auser objectForKey:@"userid"];
                user.userRole = [auser objectForKey:@"userRole"];
                user.name = [auser objectForKey:@"nickname"];
                NSLog(@"nickname==== %@", user.name);
                //如果是当前用户，不添加
                if ([staticInfo.user.userId longLongValue]==[user.userId longLongValue]) {
                    staticInfo.user.userRole = user.userRole;
                }
                staticInfo.user.isLeader=FALSE;
                if([staticInfo.user.userRole isEqualToNumber:[[NSNumber alloc]initWithInt:20]]){
                    staticInfo.user.isLeader=TRUE;
                    user.isLeader=TRUE;
                }
                if(![[auser objectForKey:@"bavatorUrl"] isEqualToString:@""]){
                    user.bavatorUrl=[auser objectForKey:@"bavatorUrl"];
                }
                if(![[auser objectForKey:@"savatorUrl"] isEqualToString:@""]){
                    user.savatorUrl=[auser objectForKey:@"savatorUrl"];
                }
                if(![[auser objectForKey:@"nickname"] isEqualToString:@""]){
                    user.name=[auser objectForKey:@"nickname"];
                }
                [self.userArray addObject:user];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setUserScrollView];
            _userInited=TRUE;
            if(_routesInited&&_userInited){
                [loadingView setHidden:YES];
            }
        });
    });
}
//定时发送我的当前位置
-(void)sendMyLocationQuartz{
    [self.myLocation startUpdatingLocation];
    dispatch_queue_t q;
    q=dispatch_queue_create("sendMyLocationQuartz", NULL);
    dispatch_async(q, ^{
        MKCoordinateRegion theRegion;
        theRegion.center = [[self.myLocation location] coordinate];
        CLLocationDegrees latitude=theRegion.center.latitude;
        CLLocationDegrees longtitude=theRegion.center.longitude;
        double speed=[self getSpeed];
        [requestUtil sendAndGetAnnotation:riddingId latitude:[NSString stringWithFormat:@"%lf",latitude] longtitude:[NSString stringWithFormat:@"%lf",longtitude] status:@"1" speend:speed isGetUsers:_isShowTeamers?1:0];
    });
}
//插入用户位置的异步回调
-(void)sendAndGetAnnotationReturn:(NSArray*)returnArray{
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    for(NSDictionary *location in returnArray){
        [dic setValue:location forKey:[[location objectForKey:@"userId"]stringValue]];
    }
    [self updateAnnotations:dic];
}

//得到当前速度
-(double)getSpeed{
    if(lastLocation==nil){
        lastLocation=[[CLLocation alloc]init];
        return 0;
    }
    CLLocation *nowLocation=[self.myLocation location];
    CLLocationDistance meters=[nowLocation distanceFromLocation:lastLocation];  
    lastLocation=[nowLocation copy];
    return (meters*3.6)/([[NSString stringWithFormat:@"%@",getToDestinationTime]doubleValue]);
}
//画路线
-(void)drawRoutes{
    dispatch_queue_t q;
    q=dispatch_queue_create("drawRoutes", NULL);
    dispatch_async(q, ^{
        line_color = [UIColor getColor:@"0048ff"];
        //如果数据库中存在，那么取数据库中的地图路径，如果不存在，http去请求服务器。
        //数据库中取出是mapTaps或者points
        NSMutableDictionary *map_dic = [[NSMutableDictionary alloc]init];
        map_dic = [requestUtil getMapMessage:riddingId];
        NSArray *array = [map_dic objectForKey:@"points"];
        if (!array) {
            array = [map_dic objectForKey:@"mapTaps"];
            if(!array){
                [self.navigationController popViewControllerAnimated:YES];
            }
            //基本不会使用了 by zys 20120719
            [[MapUtil getSinglton] calculate_routes_from:array map_dic:map_dic];
            if(map_dic){
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"错误提示" 
                                                                message:@"生成地图失败。" 
                                                               delegate:self cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
            array = [map_dic objectForKey:@"points"];
            [requestUtil sendMapPoiont:riddingId point:array mapId:[map_dic objectForKey:@"id"] distance:[map_dic objectForKey:@"distance"]];
        }
        float dis = [[map_dic objectForKey:@"distance"] intValue]*1.0/1000;
        self.routes = [[MapUtil getSinglton] decodePolyLineArray:[map_dic objectForKey:@"points"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.distanceLabel.text = [NSString stringWithFormat:@"总距离:%0.2lf km",dis];
            [[MapUtil getSinglton] update_route_view:mapView to:self.route_view line_color:line_color routes:self.routes];
            [[MapUtil getSinglton] center_map:mapView routes:self.routes];
            CLLocation* startLocation=[self.routes objectAtIndex:0];
            [self addStartAnnotationWithcoordinateX:startLocation.coordinate.latitude coordinateY:startLocation.coordinate.longitude Title:@"title1" Subtitle:@"subtitle1"];
            CLLocation* endLocation=[self.routes objectAtIndex:[self.routes count]-1];
            [self addEndAnnotationWithcoordinateX:endLocation.coordinate.latitude coordinateY:endLocation.coordinate.longitude Title:@"title2" Subtitle:@"subtitle2"];
            _routesInited=YES;
            if(_routesInited&&_userInited){
                [loadingView setHidden:YES];
            }
        });
        [self setRiddingLocationToDB:map_dic];
    });
}

-(void)myLocationQuartz{
    MKCoordinateRegion region = mapView.region;
    region.span.latitudeDelta=10;
    region.span.longitudeDelta=10; 
    NSTimeInterval time=[[NSString stringWithFormat:@"%@",sendMyLocationTime]doubleValue];
    sendMyLocationTimer=[NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(sendMyLocationQuartz) userInfo:nil repeats:YES];
    [sendMyLocationTimer fire];
}

-(void)goToDestinationQuartz{
    double time=[[NSString stringWithFormat:@"%@",getToDestinationTime]doubleValue];
    getToDestinationTimer=[NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(getToDestinationDistance) userInfo:nil repeats:YES];
    [getToDestinationTimer fire];
}

-(void) addStartAnnotationWithcoordinateX:(double)coorX coordinateY:(double)coorY   
              Title:(NSString*)title Subtitle:(NSString*)subtitle{  
    CLLocationCoordinate2D startPoint;   
    if(coorX && coorY){   
        startPoint.latitude = coorX;   
        startPoint.longitude = coorY;   
        startAnnotation = [[StartAnnotation alloc] initWithCoords:startPoint];    
        
        if(title!=NULL)   
            startAnnotation.title = title;
        if(subtitle!=NULL)   
            startAnnotation.subtitle = subtitle;   
        [self.mapView addAnnotation:startAnnotation];
    }   
}
-(void) addEndAnnotationWithcoordinateX:(double)coorX coordinateY:(double)coorY   
                                     Title:(NSString*)title Subtitle:(NSString*)subtitle{  
    CLLocationCoordinate2D endPoint;   
    if(coorX && coorY){   
        endPoint.latitude = coorX;   
        endPoint.longitude = coorY;   
        endAnnotation = [[EndAnnotation alloc] initWithCoords:endPoint];    
        if(title!=NULL)   
            endAnnotation.title = title;
        if(subtitle!=NULL)   
            endAnnotation.subtitle = subtitle;  
        [self.mapView addAnnotation:endAnnotation];
    }   
}

//插入骑行的经纬度等信息到数据库
-(void)setRiddingLocationToDB:(NSMutableDictionary*)map_dic{
    dispatch_queue_t q;
    q=dispatch_queue_create("setRiddingLocationToDB", NULL);
    dispatch_async(q, ^{
        if([[RiddingLocationDao getSinglton] getRiddingLocationCount:riddingId]>0){
            return;
        }
        if([[map_dic objectForKey:@"startLocations"] count]==0){
            NSArray *array = [map_dic objectForKey:@"mapTaps"];
            if(!array||[array count]==0){
                return;
            }
            [[MapUtil getSinglton] calculate_routes_from:array map_dic:map_dic];
        }
        if([[map_dic objectForKey:@"startLocations"] count]!=[[map_dic objectForKey:@"toNextDistance"] count]){
            return;
        }
        NSMutableArray *locations=[[NSMutableArray alloc]init];
        int index=0;
        for(CLLocation *location in [map_dic objectForKey:@"startLocations"]){
            RiddingLocation *riddingLocation=[[RiddingLocation alloc]init];
            riddingLocation.latitude=location.coordinate.latitude;
            riddingLocation.longtitude=location.coordinate.longitude;
            riddingLocation.riddingId=riddingId;
            riddingLocation.toNextDistance=[[map_dic objectForKey:@"toNextDistance"] objectAtIndex:index];
            riddingLocation.weight=[NSNumber numberWithInt:index++];
            [locations addObject:riddingLocation];
        }
        [[RiddingLocationDao getSinglton] addRiddingLocation:riddingId locations:locations];
    });
}

//插入用户坐标 
-(void)updateAnnotations:(NSMutableDictionary*)locations{
    if(locations==nil||self.userArray==nil){
        return;
    }
    NSMutableDictionary* annotationDic=[[NSMutableDictionary alloc]init];
    NSArray* annotations=[mapView annotations];
    if(annotations&&[annotations count]>0){
        for(id<MKAnnotation> annotation in annotations){
            if ([annotation isKindOfClass:[UserAnnotation class]]){
                UserAnnotation* userAnnotation=(UserAnnotation*)annotation;
                [annotationDic setValue:userAnnotation forKey:[NSString stringWithFormat:@"%@",userAnnotation.userId]];
            }
        }
    }
    dispatch_queue_t q;
    q=dispatch_queue_create("updateAnnotations", NULL);
    for (User *user in self.userArray) {
        //如果是当前用户
        if([user.userId longLongValue]==[staticInfo.user.userId longLongValue]){
            continue;
        }
        dispatch_async(q, ^{
            NSDictionary *dic=[locations objectForKey:[NSString stringWithFormat:@"%@",user.userId]];
            if (dic!=nil) {
                CLLocationDegrees latitude=[[dic objectForKey:@"latitude"] doubleValue];
                CLLocationDegrees longtitude=[[dic objectForKey:@"longtitude"] doubleValue];
                CLLocationCoordinate2D coordinate2D=CLLocationCoordinate2DMake(latitude, longtitude);
                user.speed=[[dic objectForKey:@"speed"]doubleValue];
                user.status=[[dic objectForKey:@"status"]intValue];
                UserAnnotation* userAnnotation=[annotationDic objectForKey:[NSString stringWithFormat:@"%@",user.userId]];
                if(!userAnnotation){
                    userAnnotation=[[UserAnnotation alloc]init];
                    userAnnotation.userId=user.userId;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [mapView addAnnotation:userAnnotation];
                    });
                }
                userAnnotation.headImage=[user getSSavator];
                userAnnotation.coordinate=coordinate2D;
                userAnnotation.subtitle=[NSString stringWithFormat:@"更新时间:%@",[dic objectForKey:@"timebefore"]];
                userAnnotation.title = user.name;
                user.annotation=userAnnotation;
            }
        });
    }
    for(UIView *view in [self.userScrollView subviews]){
        if([view isKindOfClass:[UserView class]]){
            UserView *userView=(UserView*)view;
            NSDictionary *dic=[locations objectForKey:[NSString stringWithFormat:@"%@",userView.user.userId]];
            [userView changeStatus:[[dic objectForKey:@"status"]intValue]];
        }
    }
}

//放大地图按钮点击
-(void)expandViewClick:(UITapGestureRecognizer*) gestureRecognize{
    MKCoordinateRegion region = mapView.region;
    region.span.latitudeDelta=region.span.latitudeDelta / 2;
    region.span.longitudeDelta=region.span.longitudeDelta / 2;
    [mapView setRegion:region animated:YES];
}
//缩小地图按钮点击
-(void)reductViewClick:(UITapGestureRecognizer*) gestureRecognize{
    MKCoordinateRegion region = mapView.region;
    region.span.latitudeDelta=region.span.latitudeDelta * 2;
    region.span.longitudeDelta=region.span.longitudeDelta * 2;
    [mapView setRegion:region animated:YES];
}

-(void)removeAllAnnotations{
    if(mapView){
        NSArray* annotations=[mapView annotations];
        if(annotations&&[annotations count]>0){
            for(id<MKAnnotation> annotation in annotations){
                if (![annotation isKindOfClass:[MKUserLocation class]]&&![annotation isKindOfClass:[StartAnnotation class]]&&![annotation isKindOfClass:[EndAnnotation class]]){
                    [mapView removeAnnotation:annotation];
                }
            }
        }
    }
}

//重新加载当前位置
-(void)reLocationClick:(UITapGestureRecognizer*) gestureRecognize{
    [self sendMyLocationQuartz];
    MKCoordinateRegion region;
    region.center = self.myLocation.location.coordinate;
    region.span = mapView.region.span;
    [mapView setRegion:region animated:YES];
}

/**
 **
 **点击操作
 **/
#pragma mark -
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    beginPoint = [touch locationInView:self.view];
    if(touch.view==self.userTapView){
        self.userTapView.image = [UIImage imageNamed:@"toolBarSelected.png"];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (_isAnimationing) {
        return;
    }
    UITouch *touch = [touches anyObject];
    CGPoint currentPosition = [touch locationInView:self.view];
    
    CGFloat offsetW = currentPosition.x - beginPoint.x;
    CGFloat offsetH = currentPosition.y - beginPoint.y;
    
    self.userTapView.image = [UIImage imageNamed:@"toolBar.png"];
    
    if (fabsf(offsetW) > fabsf(offsetH)) {
        //向右移动,并且点击的是显示用户列表的view
        if(offsetW >10&&touch.view==self.userTapView){
            //[self membersViewDownToUp:offsetW];
        }else if(offsetW <-10 &&touch.view==self.userScrollView){
            //从下向上滑动
        }
    }
    else if (fabsf(offsetH) > fabsf(offsetW)) {
        if (offsetH < -10 && touch.view == self.userTapView) {
            [self membersViewDownToUp];
        }
        else if(offsetH >10 && touch.view == self.userTapView)
            [self membersViewUpToDown];
    }
}
//animation停止
-(void) myAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
    _isAnimationing=FALSE;
}

/**
 **(begin)
 **userScrollView相关模块
 **/
//插入用户滚动view
-(void)setUserScrollView{
    isShowDelete=FALSE;
    int width=70;
    int height=70;
    int index=1;
    int outheight=height+10;
    int outWidth=width+10;
    int addViewCount=1;
    //如果不是队长是成员
    if(!staticInfo.user.isLeader||[self.riddingStatus isEqualToNumber:[NSNumber numberWithInt:20]]){
        addViewCount=0;
        index=0;
    }
    UIImageView *imageView=[[UIImageView alloc]init];
    [imageView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"memberBackground.png"]]];
    [self.userScrollView addSubview:imageView];
    if(self.userArray&&[self.userArray count]>4){
        [imageView setFrame:CGRectMake(0, 0, outWidth*([self.userArray count]+addViewCount), self.userScrollView.frame.size.height)];
    }
    UIView *outActionView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, outWidth, outheight)];
    outActionView.userInteractionEnabled=YES;
    UITapGestureRecognizer *viewTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actionViewClick:)];
    [outActionView addGestureRecognizer:viewTap]; 
    if(staticInfo.user.isLeader&&![self.riddingStatus isEqualToNumber:[NSNumber numberWithInt:20]]){
        UIImageView *actionview=[[UIImageView alloc]initWithFrame:CGRectMake(10, 15, 60, 60)];
        UIImage *image=[UIImage imageNamed:@"addUser.png"];
        actionview.image=image;
        [outActionView addSubview:actionview];
    }
    [self.userScrollView addSubview:outActionView];
    self.userScrollView.contentSize = CGSizeMake(width, outheight);
    if (self.userArray&&[self.userArray count]>0) {
        for (User *user in self.userArray) {
            UserView *userView=[[UserView alloc]initWithFrame:CGRectMake(5+(outWidth)*(index++), 5, width, height)];
            userView.user=user;
            userView.userViewDelegate=self;
            userView=[userView init];
            userView.backgroundColor = [UIColor clearColor];
            [self.userScrollView addSubview:userView];
        }
        self.userScrollView.contentSize = CGSizeMake((outWidth)*([self.userArray count]+addViewCount), height);
    }
    self.userScrollView.bounces=YES;
    UILongPressGestureRecognizer *longTap =[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longViewClick:)];
    longTap.minimumPressDuration = 0.3;
    [self.userScrollView addGestureRecognizer:longTap];
}
//长按
-(void)longViewClick:(UITapGestureRecognizer*)gestureRecognize{
    if (staticInfo.user.isLeader) {
        isShowDelete=TRUE;
        NSArray *array=[self.userScrollView subviews];
        if(array&&[array count]>0){
            for(UIView *view in array){
                if([view isKindOfClass:[UserView class]]){
                    UserView *userView=(UserView*)view;
                    userView.deleteView.hidden=NO;
                }
            }
        }
    }
}

//userView.h的代理,点击头像后在地图中间显示
-(void)avatorViewClick:(UITapGestureRecognizer*) gestureRecognize userId:(NSString*)userId{
    if([userId longLongValue]==[staticInfo.user.userId longLongValue]){
        return;
    }
    if(self.userArray){
        for(User *user in self.userArray){
            if([userId longLongValue]==[user.userId longLongValue]){
                MKCoordinateRegion region;
                region.center.latitude=user.annotation.coordinate.latitude;
                region.center.longitude=user.annotation.coordinate.longitude;
                region.span=mapView.region.span;
                [mapView setRegion:region animated:YES];
                [mapView selectAnnotation:user.annotation animated:YES];
                break;
            }
        }
    }
}

//userView.h代理
-(void)deleteViewClick:(UITapGestureRecognizer*) gestureRecognize userView:(UserView*)userView{
     [MobClick event:@"2012070205"];
    CGFloat x=userView.frame.origin.x;
    [requestUtil deleteRiddingUser:riddingId deleteUserIds:[[NSArray alloc]initWithObjects:userView.user.userId, nil]];
    if(self.userScrollView){
        [userView removeFromSuperview];
        NSArray* userView=[self.userScrollView subviews];
        for(UIView *view in userView){
            if(view.frame.origin.x>x){
                [UIView beginAnimations:nil context:NULL];
                [UIView setAnimationDuration:0.4f];
                [UIView setAnimationDelegate:self];
                [view setFrame:CGRectMake(view.frame.origin.x-view.frame.size.width-10, view.frame.origin.y, view.frame.size.width, view.frame.size.height)];
                [UIView commitAnimations];
            }
        }
    }
    if(self.userArray&&[self.userArray count]>0){
        NSMutableArray *tempArray=[[NSMutableArray alloc]init];
        for (User *user in self.userArray) {
            if([user.userId longLongValue]!=[userView.user.userId longLongValue]){
                [tempArray addObject:user];
            }
        }
        self.userArray=tempArray;
    }
}
//删除所有UserView
-(void)removeAllUserView{
    if(self&&self.userScrollView&&[self.userScrollView.subviews count]>0){
        NSArray *array=[self.userScrollView subviews];
        for(UIView *view in array){
            [view removeFromSuperview];
        }
    }
    [self removeAllAnnotations];
    self.userArray=[[NSMutableArray alloc]init];
}
//添加用户按钮
-(void)actionViewClick:(UITapGestureRecognizer*) gestureRecognize{
    [MobClick event:@"2012070203"];
    InvitationViewController* invitationView=[[InvitationViewController alloc]init];
    invitationView.riddingId=self.riddingId;
    _userInited=FALSE;
    loadingView=[[ActivityView alloc]init:@"获取队员信息" lat:self.view.frame.size.width/2 log:self.view.frame.size.height/2];
    loadingView.hidden=NO;
    [self.view addSubview:loadingView];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSMutableArray* userIdArray=[[NSMutableArray alloc]init];
        for(User *user in self.userArray){
            [userIdArray addObject:user.userId];
        }
        NSDictionary* dic=[requestUtil getAccessUserId:userIdArray souceType:1];
        dispatch_async(dispatch_get_main_queue(), ^{
            for(User *user in self.userArray){
                NSNumber* accessUserId=[dic objectForKey:user.userId];
                if(accessUserId){
                    user.accessUserId=[NSString stringWithFormat:@"%@",accessUserId];
                    [invitationView.selectedDic setValue:user forKey:user.accessUserId];
                    [invitationView.originalDic setValue:user.userId forKey:user.accessUserId];
                }
            }
            [self.navigationController pushViewController:invitationView animated:YES];
            loadingView.hidden=YES;
        });
    });
    [self membersViewUpToDown];
    
    
}
#pragma mark - Animation for Member Views
//点击地图后，scrollview隐藏显示的信息操作 
-(void)mapViewClick:(UITapGestureRecognizer*) gestureRecognize{
    if (_isUserTapViewOut==TRUE) {
        [self membersViewUpToDown];
        _isUserTapViewOut=FALSE;
        NSArray *array=[self.userScrollView subviews];
        if(array&&[array count]>0){
            for(UIView *view in array){
                if([view isKindOfClass:[UserView class]]){
                    UserView *userView=(UserView*)view;
                    userView.deleteView.hidden=YES;
                }
            }
        }
        [mapView deselectAnnotation:showingAnnotation animated:YES];
        isShowDelete=FALSE;
    }
}

//用户从下往上滑userTap
-(void)membersViewDownToUp
{
    if(!_userInited||!_routesInited){
        return;
    }
    _isAnimationing = YES;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3f];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(myAnimationDidStop:finished:context:)];
    [self.userScrollView setFrame:CGRectMake(0, 460-self.userScrollView.frame.size.height, self.view.frame.size.width, self.userScrollView.frame.size.height)];
    [self.userTapView setFrame:CGRectMake(0, 332, 320, 36)];
    [self.showMemberButton setFrame:CGRectMake(8, 322, 38, 38)];
    [self.membersStatusView setFrame:CGRectMake(8, 322, 38, 38)];
    [UIView commitAnimations];
    _isUserTapViewOut=TRUE;
}
-(void)membersViewUpToDown{
    _isAnimationing = YES;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3f];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(myAnimationDidStop:finished:context:)];
    [self.userScrollView setFrame:CGRectMake(0, 460, self.userScrollView.frame.size.width, self.userScrollView.frame.size.height)];
    [self.userTapView setFrame:CGRectMake(0, 425, 320, 36)];
    [self.showMemberButton setFrame:CGRectMake(8, 415, 38, 38)];
    [self.membersStatusView setFrame:CGRectMake(8, 415, 38, 38)];
    [UIView commitAnimations];
    _isUserTapViewOut=FALSE;
}
/**
 **(end)
 **userScrollView相关模块
 **/
//annotation
//地图移动的时候的操作
#pragma mark mapView delegate functions
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
    self.route_view.hidden = YES;
    [self.mapView deselectAnnotation:showingAnnotation animated:YES];
}
//地图移动结束后的操作
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    [[MapUtil getSinglton] update_route_view:self.mapView to:self.route_view line_color:line_color routes:self.routes];
    self.route_view.hidden = NO;
    [self.route_view setNeedsDisplay];
}
//选中某个annotation时
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view NS_AVAILABLE(NA, 4_0){
    showingAnnotation=view.annotation;
}
//取消选中某个annotation时
- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view NS_AVAILABLE(NA, 4_0){
    NSLog(@"deselect");
}
//在addAnnotation的时候调用
- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    if ([annotation isKindOfClass:[StartAnnotation class]]) {
        MKAnnotationView *newAnnotation=[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"annotationStart"];
        newAnnotation.image = [UIImage imageNamed:@"起点.png"];
        newAnnotation.canShowCallout = NO;  
        return newAnnotation;
    }
    
   if ([annotation isKindOfClass:[EndAnnotation class]]) {
        MKAnnotationView *newAnnotation=[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"annotationEnd"];  
        newAnnotation.image = [UIImage imageNamed:@"终点.png"];
        newAnnotation.canShowCallout = NO;  
        return newAnnotation;
    }
   
    // 处理我们自定义的Annotation
    if ([annotation isKindOfClass:[UserAnnotation class]]) {  
        static NSString* travellerAnnotationIdentifier = @"TravellerAnnotationIdentifier";
        MKPinAnnotationView* pinView = (MKPinAnnotationView *)
        [mapView dequeueReusableAnnotationViewWithIdentifier:travellerAnnotationIdentifier];
        if (!pinView)
        {
            MKAnnotationView* customPinView = [[MKAnnotationView alloc]
                                               initWithAnnotation:annotation reuseIdentifier:travellerAnnotationIdentifier];
            
            [customPinView setCanShowCallout:YES]; //很重要，运行点击弹出标签
            customPinView.draggable=NO;
            UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
            [rightButton addTarget:self
                            action:@selector(showDetails:)  //点击右边的按钮之后，显示另外一个页面
                  forControlEvents:UIControlEventTouchUpInside];
            pinView.canShowCallout=YES;
            pinView.animatesDrop=YES;
            UserAnnotation *userAnnotation = (UserAnnotation *)annotation;
            UIImageView *headImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
            headImage.image=userAnnotation.headImage;
            customPinView.leftCalloutAccessoryView = headImage; //设置最左边的头像
            
            UIImage *image = [UIImage imageNamed:@"其他队友.png"];
            customPinView.image = image;
            customPinView.opaque = YES;
            return customPinView;
        }else
        {
            pinView.annotation = annotation;
        }
        return pinView;
    }
    return nil;
}

- (void) showDetails{
    
}

- (void)viewDidUnload
{
    mapView=nil;
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait||interfaceOrientation ==UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark - Button Initialization



#pragma mark - Button Responser
-(IBAction)backBtnClick:(id)sender{
    if(self){
        [self.navigationController popViewControllerAnimated:YES];
    }
}


-(IBAction)showMemberButtonClicked:(id)sender
{
    if(_isShowTeamers){
        //设置不显示
        [self removeAllAnnotations];
        _isShowTeamers=FALSE;
        self.membersStatusView.image = [UIImage imageNamed:@"showSingleUser.png"];;
    }else{
        //设置显示所有队友
        _isShowTeamers=TRUE;
        [self sendMyLocationQuartz];
        self.membersStatusView.image = [UIImage imageNamed:@"showMultipleUsers.png"];;
    }
}
-(IBAction)showLocationButtonClicked:(id)sender
{
    [self sendMyLocationQuartz];
    MKCoordinateRegion region;
    region.center=self.myLocation.location.coordinate;
    region.span=mapView.region.span;
    
    [mapView setRegion:region animated:YES];
}
-(IBAction)zoomInButtonClicked:(id)sender
{
    [MobClick event:@"2012070202"];
    if(_zooming){
        return;
    }
    MKCoordinateRegion region = mapView.region;
    region.span.latitudeDelta=region.span.latitudeDelta / 2;
    region.span.longitudeDelta=region.span.longitudeDelta / 2;
    if(region.span.latitudeDelta>0&&region.span.longitudeDelta>0){
        NSLog(@"region.span.latitudeDelta:%lf",region.span.latitudeDelta);
        [mapView setRegion:region animated:YES];
    }
    _zooming=false;
    
}
-(IBAction)zoomOutButtonClicked:(id)sender
{
    [MobClick event:@"2012070201"];
     MKCoordinateRegion region = mapView.region;
    region.span.latitudeDelta=region.span.latitudeDelta * 2;
    region.span.longitudeDelta=region.span.longitudeDelta * 2;
    if(_zooming||region.span.latitudeDelta>200){
        return;
    }
    _zooming=true;
   
    NSLog(@"region.span.latitudeDelta:%lf",region.span.latitudeDelta);
    [mapView setRegion:region animated:YES];
    _zooming=false;
}
@end
